//
//  ShopOneCollectionViewController.m
//  1243
//
//  Copyright © 2016年 1243. All rights reserved.
//

#import "ShopOneCollectionViewController.h"
#import "ShopOneCollectionViewCell.h"
#import "XRCarouselView.h"
#import "JSDropDownMenu.h"
#import "ShoperDetailViewController.h"
#import "XLPlainFlowLayout.h"
#import "NetWorkTools.h"
#import "UIImageView+WebCache.h"

#define MENU_HIGH 45

@interface ShopOneCollectionViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,XRCarouselViewDelegate>
{
    
    NSMutableArray *_data1;
    NSMutableArray *_data2;
    NSMutableArray *_data3;
    
    NSInteger _currentData1Index;
    NSInteger _currentData2Index;
    NSInteger _currentData3Index;
    
    
    NSInteger _menuIndex;
}

@property(nonatomic,strong)UICollectionViewFlowLayout *layout;

@property(nonatomic,strong)UICollectionView *ShopCollectionView;

/**
 *  头部轮播
 */
@property(nonatomic,strong)XRCarouselView *XRCarouselView;
/**
 *  头部筛选菜单
 */
@property(nonatomic,strong)UIView *headerMenuView;

/**
 *  头部筛选
 */
@property(nonatomic,strong)NSMutableArray *GoodsArray;
/**
 *  记录按钮状态
 */
@property (nonatomic,assign) BOOL isSelected;
/**
 *  排序的状态
 */
@property (nonatomic, strong) NSString *strType;

@end

@implementation ShopOneCollectionViewController

static NSString * const reuseIdentifier = @"shopOneCell";



- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self addCollectView];
    
    [self addBackBtn];
    
    if (self.num == 1) {
        [self loadMerchant];
    } else {
        [self getShoesAndColorData];
    }
    
    [self setupDefaultData];
}

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    
//    self.strType = @"3";
    
}

- (void)loadMerchant {
    
    NSDictionary *dict = @{
                           @"MerchantId":self.merchantId,
                           @"SortName":@"",
                           @"PageIndex":@"1",
                           @"PageSize":@"10",
                           @"Postion":@(0),
                           };
    
    [[NetWorkTools sharedNetWorkTools] objectWithURLDict:dict AndMenthodName:@"PRODUCTLISTQUERY" completeBlock:^(id object) {
        
        NSLog(@"%@",object);
        NSString *DataString = [object objectForKey:@"BackData"];
        
        NSDictionary *dict = [NetWorkTools dictionaryWithJsonString:DataString];
        
        [self.GoodsArray removeAllObjects];
        
        [self.GoodsArray addObjectsFromArray:dict[@"ds"]];
        
        [self.ShopCollectionView reloadData];
        
        NSLog(@"%@", dict);
        
    }];
}

- (void)loadData {
    NSDictionary *dict = @{
                           @"SortName":@"粮油",
                           @"StrType":self.strType,
                           @"PageIndex":@"1",
                           @"PageSize":@"10"
                           
                           };
    
    [[NetWorkTools sharedNetWorkTools] objectWithURLDict:dict AndMenthodName:@"PRODUCTLISTQUERY" completeBlock:^(id object) {
        
        NSLog(@"%@",object);
        NSString *DataString = [object objectForKey:@"BackData"];
        
        NSDictionary *dict = [NetWorkTools dictionaryWithJsonString:DataString];
        
        [self.GoodsArray removeAllObjects];
        
        [self.GoodsArray addObjectsFromArray:dict[@"ds"]];
        
        [self.ShopCollectionView reloadData];
        
        NSLog(@"%@", dict);
        
    }];
    
}

- (void)setupDefaultData
{
    _menuIndex = 1000;
}

/**
 *  添加返回按钮
 */
- (void)addBackBtn
{
    UIView *backBgView = [[UIView alloc] initWithFrame:CGRectMake(WEITH/6*5, HEIGHT/5*4, 30, 30)];
    [self.view addSubview:backBgView];
    
    backBgView.layer.borderWidth = 1;
    backBgView.layer.borderColor = COLOR(128, 128, 128, 1).CGColor;
    backBgView.backgroundColor = [UIColor blackColor];
    backBgView.alpha = 0.6;
    
    
    UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(WEITH/6*5 + 5,  HEIGHT/5*4 +5, 20, 20);
    [self.view addSubview:button];
    [button setImage:[UIImage imageNamed:@"backTop"] forState:UIControlStateNormal];
    //    [button setImage:[UIImage imageNamed:@"backTop"] forState:UIControlStateHighlighted];
    [button addTarget:self action:@selector(backBtnClick) forControlEvents:UIControlEventTouchUpInside];
}

- (void)backBtnClick
{
    if (self.GoodsArray.count) {
        
        NSIndexPath *firstIndex = [NSIndexPath indexPathForItem:1 inSection:1];
        
        [self.ShopCollectionView selectItemAtIndexPath:firstIndex animated:YES scrollPosition:UICollectionViewScrollPositionTop];
    }

}


- (void)addCollectView
{
    self.edgesForExtendedLayout = UIRectEdgeNone;
    
    CGFloat margin = 5;
    XLPlainFlowLayout *flowlayout = [[XLPlainFlowLayout alloc] init];
    flowlayout.itemSize = CGSizeMake(WEITH/2 - margin/2,HEIGHT/2.5 + 20);
    flowlayout.minimumLineSpacing = margin;
    flowlayout.minimumInteritemSpacing = margin;
    flowlayout.naviHeight = 0;
    flowlayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    
    UICollectionView * ShopCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, WEITH, HEIGHT) collectionViewLayout:flowlayout];
    
    self.ShopCollectionView = ShopCollectionView;
    self.ShopCollectionView.delegate = self;
    self.ShopCollectionView.dataSource = self;
    self.ShopCollectionView.backgroundColor = BACKGROUND_COLOR;
    [self.view addSubview:self.ShopCollectionView];
    
    [self.ShopCollectionView registerNib:[UINib nibWithNibName:@"ShopOneCollectionViewCell" bundle:[NSBundle mainBundle]] forCellWithReuseIdentifier:reuseIdentifier];
    //注册表头
    [self.ShopCollectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header"];
    
    
}

#pragma mark >>>>>>>>>筛选菜单按钮点击
- (void)menuBtnClick:(UIButton *)button{
#warning 第一次点击的时候逻辑出错！！！！！！！
    _menuIndex = button.tag;
    if (button.tag == 1000) {
        NSLog(@"%ld",_menuIndex);
        if (button.selected == NO) {
            self.strType = @"3";
        }
        [self buttonSelectedBgColor:button];
    }else if (button.tag == 1001) {
        NSLog(@"%ld",_menuIndex);
        if (button.selected == NO) {
            self.strType = @"1";
        }
        [self buttonSelectedBgColor:button];
    }else{
        NSLog(@"%ld",_menuIndex);
        
        [self buttonSelectedBgColor:button];
    }
    
    [self.ShopCollectionView reloadData];
}

- (void)buttonSelectedBgColor:(UIButton *)button{
    
    for (UIButton *btn in self.headerMenuView.subviews) {
        if (btn.tag == button.tag) {
            if ([self.strType isEqualToString:@"1"] || [self.strType isEqualToString:@"3"]) {
                [btn setImage:[UIImage imageNamed:@"shanghong"] forState:UIControlStateNormal];
                if ([self.strType isEqualToString:@"1"]) {
                    self.strType = @"2";
                }
                if ([self.strType isEqualToString:@"3"]) {
                    self.strType = @"4";
                }
            } else {
                [btn setImage:[UIImage imageNamed:@"xiahong"] forState:UIControlStateNormal];
                if ([self.strType isEqualToString:@"2"]) {
                    self.strType = @"1";
                }
                if ([self.strType isEqualToString:@"4"]) {
                    self.strType = @"3";
                }
            }
            
            btn.selected = YES;
            [btn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
            [self loadData];
        }else{
            btn.selected = NO;
            [btn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
            [btn setImage:[UIImage imageNamed:@"huise"] forState:UIControlStateNormal];
        }
    }
}


#pragma mark - XRCarouselViewDelegate
- (void)carouselView:(XRCarouselView *)carouselView didClickImage:(NSInteger)index {
    NSLog(@"点击了第%ld张图片", index);
}

#pragma mark <UICollectionViewDataSource>
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 2;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (section == 0) {
        return 0;
    }
    return self.GoodsArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    ShopOneCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
    
    NSString *URLString = @"http://120.76.162.124:8083";
    NSString *PicString = [URLString stringByAppendingString:[self.GoodsArray[indexPath.row] objectForKey:@"PictureURL"]];
    
    [cell.ShopImage sd_setImageWithURL:[NSURL URLWithString:PicString] placeholderImage:[UIImage imageNamed:@"shopZanweitu"]];
    //    cell.ShopImage.contentMode = UIViewContentModeScaleAspectFit;
    
    cell.shopNameLabel.text = [self.GoodsArray[indexPath.row] objectForKey:@"Title"];
    cell.saleLabel.text = @"已售9999";
    cell.priceLabel.text = [NSString stringWithFormat:@"%@",[self.GoodsArray[indexPath.row] objectForKey:@"SellPrice"]];
    
    return cell;
}

#pragma mark <UICollectionViewDelegate>
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    ShoperDetailViewController *detailVC = [[ShoperDetailViewController alloc] init];
    detailVC.xingYingShopID = [self.GoodsArray[indexPath.row] objectForKey:@"Id"];
    [self.navigationController pushViewController:detailVC animated:YES];
    NSLog(@"%zd",indexPath.row);
}

#pragma mark---加载UICollectionView表头
-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    UICollectionReusableView *reusableView = nil;
    if ([collectionView isEqual:self.ShopCollectionView]) {
        
        if ([kind isEqualToString:UICollectionElementKindSectionHeader]) { // header
            
            if (indexPath.section == 0) {
                reusableView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"header" forIndexPath:indexPath];
                
                [reusableView addSubview:self.XRCarouselView];
                return reusableView;
            } else {
                reusableView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"header" forIndexPath:indexPath];
                //                [self creatHeaderView:reusableView];
                
                [reusableView addSubview:self.headerMenuView];
                //                reusableView.backgroundColor = [UIColor whiteColor];
                return reusableView;
            }
        }
        
        [self.ShopCollectionView reloadData];
        
    }
    
    return nil;
    
}

//header组头大小
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return CGSizeMake(WEITH,HEIGHT/4);
    }
    
    CGSize size={WEITH,MENU_HIGH};
    return size;
}


//tabBar 隐藏
- (void)pushForm:(UINavigationController *)pushForm pushToAndHidden:(UIViewController *)pushToVC
{
    [pushToVC setHidesBottomBarWhenPushed:YES];
    [pushForm pushViewController:pushToVC animated:YES];
    
}

- (void)getShoesAndColorData{
    
    NSDictionary *dict = @{
                           @"SortName":@"粮油",
                           @"StrType":@"4",
                           @"PageIndex":@"1",
                           @"PageSize":@"10"
                           
                           };
    
    [[NetWorkTools sharedNetWorkTools] objectWithURLDict:dict AndMenthodName:@"PRODUCTLISTQUERY" completeBlock:^(id object) {
        
        NSLog(@"%@",object);
        NSString *DataString = [object objectForKey:@"BackData"];
        
        NSDictionary *dict = [NetWorkTools dictionaryWithJsonString:DataString];
        
        self.GoodsArray = [dict objectForKey:@"ds"];
        
        //                NSLog(@"%@",object);
        //                self.GoodsArray = [NetWorkTools arrayWithJsonString:[object objectForKey:@"BackData"]];
        
        NSLog(@"%@",self.GoodsArray);
        
        [self.ShopCollectionView reloadData];
        
    }];
    
}

//- (void)getShoesAndColorData{
//
//    NSDictionary *dict = @{};
//
//    [[NetWorkTools sharedNetWorkTools] objectWithURLDict:dict AndMenthodName:@"PRODUCTLISTQUERY" completeBlock:^(id object) {
//
//        NSString *DataString = [object objectForKey:@"BackData"];
//
//        NSDictionary *dict = [NetWorkTools dictionaryWithJsonString:DataString];
//
//        self.xingYingGoodsArray = [dict objectForKey:@"ds"];
//
//        //        NSLog(@"%@",object);
//        //        self.xingYingGoodsArray = [NetWorkTools arrayWithJsonString:[object objectForKey:@"BackData"]];
//
//        NSLog(@"%@",self.xingYingGoodsArray);
//
//        [self.ShoeColllectionview reloadData];
//
//        //        NSDictionary *dict = array[0];
//        //        NSString *str = dict[@"Title"];
//
//        //        NSLog(@"%@",str);
//    }];
//
//}



// 将JSON串转化为字典或者数组
- (id)toArrayOrNSDictionary:(NSData *)jsonData{
    NSError *error = nil;
    id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData
                                                    options:NSJSONReadingAllowFragments
                                                      error:&error];
    
    if (jsonObject != nil && error == nil){
        return jsonObject;
    }else{
        // 解析错误
        return nil;
    }
}


#pragma mark >>>>>>>>>>>懒加载
- (NSMutableArray *)GoodsArray
{
    if (!_GoodsArray) {
        _GoodsArray = [NSMutableArray array];
    }
    return _GoodsArray;
}


- (UIView *)headerMenuView{
    if (!_headerMenuView) {
        
        _headerMenuView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WEITH, 45)];
        
        NSArray *arr = @[@"综合", @"价格"];
        for (int i = 0; i < 2; i ++) {
            UIButton *menuBtn = [UIButton buttonWithType:UIButtonTypeCustom];
            [menuBtn setFrame:CGRectMake(WIDTH / 2 * i, 0, WIDTH / 2, 45)];
            [menuBtn setTitle:arr[i] forState:UIControlStateNormal];
            [menuBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
            [menuBtn setImage:[UIImage imageNamed:@"huise"] forState:UIControlStateNormal];
            [menuBtn setImageEdgeInsets:UIEdgeInsetsMake(0, 80, 0, 0)];
            if (i == 0) {
                [menuBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
                [menuBtn setImage:[UIImage imageNamed:@"shanghong"] forState:UIControlStateNormal];
            }
            
            [menuBtn setBackgroundColor:[UIColor whiteColor]];
            
            menuBtn.titleLabel.font = [UIFont systemFontOfSize:15];
            menuBtn.layer.borderColor  = BACKGROUND_COLOR.CGColor; //要设置的颜色
            menuBtn.layer.borderWidth = 0.3; //要设置的描边宽
            
            [menuBtn addTarget:self action:@selector(menuBtnClick:) forControlEvents:UIControlEventTouchUpInside];
            menuBtn.tag = 1000 + i;
            [self.headerMenuView addSubview:menuBtn];
            
        }
        
    }
    return _headerMenuView;
}

- (XRCarouselView *)XRCarouselView
{
    if (!_XRCarouselView) {
        
        //轮播
        NSArray *imageArr = @[
                              [UIImage imageNamed:@"fjsj_banner1_02"],
                              [UIImage imageNamed:@"fjsj_banner2_02"],
                              [UIImage imageNamed:@"fjsj_banner3_02"]
                              ];
        
        _XRCarouselView = [XRCarouselView carouselViewWithFrame:CGRectMake(0,0, WIDTH, HEIGHT/4) imageArray:imageArr];
        
        _XRCarouselView.delegate = self;
        _XRCarouselView.time = 2;
    }
    return _XRCarouselView;
}


@end
